<template>
  <el-form ref="form" :model="user" class="form">
    <el-form-item label="用户名">
      <el-input v-model="user.username"></el-input>
    </el-form-item>
    <el-form-item label="密码">
      <el-input v-model="user.password" show-password></el-input>
    </el-form-item>
    <el-form-item label="确认密码">
      <el-input v-model="conpass" show-password></el-input>
    </el-form-item>
    <el-form-item>
      <el-button @click="register()">注册</el-button>
      <el-button type="primary" @click="login()">登录</el-button>
    </el-form-item>
</el-form>
</template>

<script>
export default {
  created() {
    
  },
  data() {
    return {
      user: {
        username: '',
        password: ''
      },
      conpass: '',
      states: ''
    }
  }, methods: {
    // 登录
    login() {
      if (this.conpass == '') {
        this.$message.error("请核对密码");
      }
      else if (this.user.password != this.conpass) {
        this.$message.error('输入密码不一致');
      } else {
        this.$axios.post("/user/login", this.user
        ).then((res) => {
          if (res.data.code == 0) {
            this.$message.error(res.data.msg);
          }
          else {
            this.$message.success("登陆成功");
            localStorage.setItem("user", JSON.stringify(res.data.data));
            this.$router.push({
              path: "/home",
            });

          }
        });
      }

    },
    // 注册
    register() {
      if (this.user.password != this.conpass) {
        this.$message.error('输入密码不一致');
      } else {
        this.$axios.post("/user/save", this.user
        ).then((res) => {
          if (res.data.code == 0) {
            this.$message.error(res.data.msg);
          } else {
            this.$message.success("注册成功");
            this.$router.push({
              path: "/home",
            });
            this.user.password = '',
              this.conpass = ''
          }

        });
      }

    }
  },
  watch: {
    $route() {
      location.reload()
    }
  }
}
</script>

<style>
.form {
  width: 50%;
  margin: auto;
}
</style>
